package com.baseframe.sys.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baseframe.common.annotation.SysLog;
import com.baseframe.common.annotation.VisitLog;
import com.baseframe.common.utils.PageUtils;
import com.baseframe.common.utils.R;
import com.baseframe.common.validator.Assert;
import com.baseframe.common.validator.ValidatorUtils;
import com.baseframe.common.validator.group.AddGroup;
import com.baseframe.common.validator.group.UpdateGroup;
import com.baseframe.sys.entity.FrameRole;
import com.baseframe.sys.entity.FrameUser;
import com.baseframe.sys.entity.FrameUserRole;
import com.baseframe.sys.service.IFrameRoleService;
import com.baseframe.sys.service.IFrameUserRoleService;
import com.baseframe.sys.service.IFrameUserService;
import com.baseframe.sys.service.dao.FrameUserRoleRepository;
import com.baseframe.sys.shiro.DefaultPasswordEncoder;

/**
 * 系统用户
 * 
 * @author mzl
 */
@RestController
@RequestMapping("/sys/user")
public class FrameUserController extends AbstractController {
	@Autowired
	private IFrameUserService sysUserService;
	@Autowired
	private IFrameUserRoleService sysUserRoleService;

	@Autowired
	private IFrameRoleService frameRoleService;

	@Autowired
	private FrameUserRoleRepository frameUserRoleRepository;

	/**
	 * 所有用户列表
	 */
	@VisitLog("所有用户列表")
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = sysUserService.queryPage(params);

		return R.ok().put("page", page);
	}

	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info() {
		return R.ok().put("user", getUser());
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog(value="修改密码", type="修改")
	@RequestMapping("/password")
	public R password(String password, String newPassword) {
		Assert.isBlank(newPassword, "新密码不为能空");

//		// 原密码
//		password = ShiroUtils.sha256(password, getUser().getSalt());
//		// 新密码
//		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
		DefaultPasswordEncoder dp = new DefaultPasswordEncoder("MD5");
		 password = dp.encode(password);
		 newPassword= dp.encode(newPassword);
		
		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserguid(), password,
				newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	public R info(@PathVariable("userId") String userId) {
		FrameUser user = sysUserService.selectById(userId);

		return R.ok().put("user", user);
	}

	/**
	 * 保存用户
	 */
	@SysLog(value="保存用户", type="新增")
	@RequestMapping("/save")
	public R save(@RequestBody FrameUser user) {
		ValidatorUtils.validateEntity(user, AddGroup.class);

		sysUserService.save(user);

		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@SysLog(value="修改用户", type="修改")
	@RequestMapping("/update")
	public R update(@RequestBody FrameUser user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		sysUserService.update(user);

		return R.ok();
	}
	
	
	
	/**
	 * 修改用户
	 */
	@SysLog(value="修改用户", type="修改")
	@RequestMapping("/updateuser")
	public R updateuser(@RequestBody FrameUser user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		sysUserService.updateUser(user);

		return R.ok();
	}

	/**
	 * 删除用户
	 */
	@SysLog(value="删除用户", type="删除")
	@RequestMapping("/delete")
	public R delete(@RequestBody String[] userIds) {
		if (ArrayUtils.contains(userIds, 1L)) {
			return R.error("系统管理员不能删除");
		}

		if (ArrayUtils.contains(userIds, getUserguid())) {
			return R.error("当前用户不能删除");
		}
		for (String guid : userIds) {
			sysUserService.delete(guid);
		}

		return R.ok();
	}

	@VisitLog("查询用户角色")
	@RequestMapping("/userRoleList/{userId}")
	public R userRoleList(@PathVariable("userId") String userGuid) {
		List<FrameRole> frameRoleList = frameRoleService.findAll();
		List<FrameUserRole> frameUserRoleList = frameUserRoleRepository
				.findAllByUserguid(userGuid);

		List<String> optional = frameUserRoleList
				.stream()
				.filter(frameUserRole -> frameUserRole.getUserguid().equals(
						userGuid))
				.map(frameUserRole -> frameUserRole.getRoleguid())
				.collect(Collectors.toList());
		Map<String, Object> roleMap = new HashMap<>(1);
		roleMap.put("roleList", frameRoleList);
		roleMap.put("roleIds", optional);
		return R.ok().put("roleMap", roleMap);
	}

	
	@SysLog(value="保存用户角色关系", type="新增")
	@RequestMapping("saveUserRole")
	@Transactional
	public R saveUserRole(@RequestBody JSONObject userrole) {
		List<String> roleIds = userrole.getJSONArray("roleIds").toJavaList(
				String.class);
		String userGuid = userrole.getString("userGuid");

		frameUserRoleRepository.deleteByUserguid(
				userGuid);

		roleIds.forEach(roleGuid -> {
			FrameUserRole frameUserRole = new FrameUserRole();
			frameUserRole.setRowguid(UUID.randomUUID().toString());
			frameUserRole.setUserguid(userGuid);
			frameUserRole.setRoleguid(roleGuid);

			frameUserRole.setUpdate_time(new Date());

			frameUserRoleRepository.save(frameUserRole);
		});
		return R.ok();
	}
}
